package com.pointmi.customeraccountdao;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.transaction.annotation.Transactional;


@Transactional
public class CustomerAccountDAOImpl implements CustomerAccountDAO {

	private SessionFactory sessionFactory;

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	protected final Session getCurrentSession() {
		return sessionFactory.getCurrentSession();
	}

	public void saveOrUpdate(Customer newCustomer) {
		getCurrentSession().saveOrUpdate(newCustomer);
	}

	@SuppressWarnings({ "rawtypes" })
	public Customer findCustomerByEmail(String email) {
		Query query = getCurrentSession().createQuery(
				"from Customer where email = :email");
		query.setParameter("email", email);
		List list = query.list();
		return foundCustomer(list);
	}

	@SuppressWarnings("rawtypes")
	private Customer foundCustomer(List list) {
		Customer user = null;
		if (list.size() > 0) {
			user = (Customer) list.get(0);
		}
		return user;
	}

	@SuppressWarnings("rawtypes")
	public Customer findCustomerByEmailOrCustomerId(String email,String customerId) {
		Query query = getCurrentSession()
				.createQuery(
						"from Customer where email = :email or customerId = :customerId");
		query.setParameter("email", email);
		query.setParameter("customerId", customerId);
		List list = query.list();
		return foundCustomer(list);
	}

	public void saveOrUpdate(PasswordReset newDetails) {
		getCurrentSession().saveOrUpdate(newDetails);
	}

	@SuppressWarnings("rawtypes")
	public Customer findCustomerByEmailAndPassword(String email, String password) {
		Query query = getCurrentSession()
				.createQuery("from Customer where email = :email and password = :password");
		query.setParameter("email", email);
		query.setParameter("password", password);
		List list = query.list();
		return foundCustomer(list);
	}

}
